package com.leetcode.algorithm.y22.m09.w2;
/**
 * 2259. 移除指定数字得到的最大结果
 * 
 * https://leetcode.cn/problems/remove-digit-from-number-to-maximize-result/
 * 
 * @author jie.deng
 *
 */
class Question2259Solution01 {

	public String removeDigit(String number, char digit) {
		int len = number.length();
		StringBuilder builder = new StringBuilder(number);
		int lastIdx = number.lastIndexOf(digit);
		if (digit == '9') {
			builder.deleteCharAt(lastIdx);
		} else {
			int firstIdx = number.indexOf(digit);
			if (firstIdx == lastIdx) {
				builder.deleteCharAt(lastIdx);
			} else {
				for (int i = firstIdx; i < lastIdx; i++) {
					if (number.charAt(i) == digit && number.charAt(i) < number.charAt(i + 1)) {
						builder.deleteCharAt(i);
						break;
					}
				}
				if (builder.length() == len) {
					builder.deleteCharAt(lastIdx);
				}
			}
		}
		return builder.toString();
	}

}